import sys
import randpass
import subprocess

def add_user(user, passwd, fname):
    # 判断用户是否存在，存在则退出
    result = subprocess.run(
        f'id {user}',
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    if result.returncode == 0:
        print('用户已存在')
        exit(1)

    # 创建用户
    subprocess.run(
        f'useradd {user}',
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    # 设置密码
    subprocess.run(
        f'echo {passwd} | passwd --stdin {user}',
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    # 用户名和密码写入文件
    content = f'username: {user}\npassword: {passwd}\n'
    with open(fname, 'a') as fobj:  # a表示追加
        fobj.write(content)

if __name__ == '__main__':
    user = sys.argv[1]
    passwd = randpass.mk_pwd()
    fname = sys.argv[2]
    add_user(user, passwd, fname)
